#!/usr/bin/python
# -*- coding: utf-8 -*-

from flask_restful import Resource
from flask         import redirect,request,make_response,abort

from urllib.parse import parse_qs, urlparse

from e4ting       import log,util
from e4ting.api   import CasDoor

from e4ting.cache import TokenCache

from core.device  import UUID
from config       import FlaskConf

class WebAuthCheck(Resource):
    ''' 检查是否登录 '''
    #----------------------------------------------------------------------
    def __init__(self):
        super(WebAuthCheck, self).__init__()

    def get(self, **kwargs):
        # code 兑换token
        # self.init()
        cas = CasDoor(casdoor_host=FlaskConf.CASDOOR_HOST, client_id=FlaskConf.CASDOOR_ID, client_secret=FlaskConf.CASDOOR_SECRET)
        code  = request.args.get("code", None)
        refer = request.headers.get("referer", "")

        log.info(refer)
        log.info(code)

        if code and cas.check_code(code=code, refer=refer, client_ip=request.remote_addr):
            return ApiOK(data=cas.code_swap_token(code))

        return ApiErr(code=400,
                msg="https://mycas.e4ting.cn/login/oauth/authorize?client_id=api&response_type=code&redirect_uri={refer}&scope=read&state=casdoor",
                )

    def post(self, *args, **kwargs):
        '''
            验证token是否有效
        '''
        cas = CasDoor(casdoor_host=FlaskConf.CASDOOR_HOST, client_id=FlaskConf.CASDOOR_ID, client_secret=FlaskConf.CASDOOR_SECRET)
        token = request.headers.get("token", "")
        refer = request.headers.get("referer", "")

        if not token:
            return ApiErr(code=401,
                msg=f"https://mycas.e4ting.cn/login/oauth/authorize?client_id=api&response_type=code&redirect_uri={refer}&scope=read&state=casdoor",
                )
        # log.info(token)
        info = cas.get_user(token)
        if not info:
            return ApiErr(code=401,
                msg=f"https://mycas.e4ting.cn/login/oauth/authorize?client_id=api&response_type=code&redirect_uri={refer}&scope=read&state=casdoor",
                )
        if info.get("status", "") == "error":
            log.error(info["msg"])
            return ApiErr(code=401,
                msg=f"https://mycas.e4ting.cn/login/oauth/authorize?client_id=api&response_type=code&redirect_uri={refer}&scope=read&state=casdoor",
                )
        TokenCache(token).set(**info)
        if info["data"]["phone"]:
            uID = UUID(info["data"]["phone"])
            uid = uID.get()
            TokenCache(token).set(uid=uid)
        else:
            uid = ""
        return {
            "code"  : 200,
            "data"  : {
                "name"  : info["data"]["displayName"],
                "phone" : info["data"]["phone"],
                "avatar": info["data"]["avatar"],
                "role"  : info["data"]["type"],
                "uid"   : uid,
            },
        }